<script>
import { FormStruct } from '@/components/CertForm/index'
import { isString } from '@/utils/kris_utils'
import Popconfirm from '@/components/PopconfirmNew/popconfirm'
import FormWithDialog from '@/components/CertForm/withDialog'
import Block from '../Block'
import dayjs from 'dayjs'

export default {
  components: {
    FormWithDialog,
    Popconfirm,
    Block
  },
  props: {
    isEditing: {
      type: Boolean,
      required: true,
      default: false
    },
    value: {
      type: Array,
      required: true,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      formDialog: {
        draft: { ...FormStruct },
        visible: false,
        mode: null // EDIT || CREATE
      },
      editingIndex: null
    }
  },
  computed: {
    certificateFormatted() {
      // 日期需要单独处理
      const exclude = ['expireDate']

      // 检查器
      const checker = (value) => {
        return value === undefined ||
                       value === null ||
                       (isString(value) && value.trim() === '')
      }

      return this.data.map(item => {
        const result = this.withFallback(exclude, checker, item, '未填写')

        result['expireDate'] = result['expireDate'] ? dayjs(result['expireDate']).format('YYYY-MM-DD') : '未填写'

        return result
      })
    },
    formDialogConfirmBtnText() {
      const { formDialog } = this
      const m = { 'EDIT': '保存', 'CREATE': '添加' }

      if (formDialog.mode === null) { return '确定' }

      return m[formDialog.mode] ?? '确定'
    },
    data: {
      get() {
        return this.value
      },
      set(data) {
        this.$emit('input', data)
      }
    }
  },
  mounted() {
  },
  methods: {
    showCreateDialog() {
      this.formDialog.mode = 'CREATE'
      this.formDialog.visible = true
            this.$refs['form'].resetFields?.()
    },
    withFallback(exclude, checker, obj, fallback) {
      const reuslt = Object
        .entries(obj)
        .map(item => {
          if (exclude.indexOf(item[0]) !== -1) { return item }

          if (checker(item[1])) { item[1] = fallback }

          return item
        })

      return Object.fromEntries(reuslt)
    },
    handleFormConfirm() {
      if (this.formDialog.mode === 'EDIT') { return this.saveRecord() }

      if (this.formDialog.mode === 'CREATE') { return this.createRecord() }
    },
    closeFormDialog() {
      this.formDialog.visible = false
      this.$nextTick(() => this.$refs['form'].resetFields?.())
    },
    handleEditing(index, row) {
      this.formDialog = {
        draft: { ...this.data[index] },
        mode: 'EDIT',
        visible: true
      }
      this.editingIndex = index
    },

    saveRecord() {
      this.$set(this.data, this.editingIndex, { ...this.formDialog.draft })
      this.editingIndex = null
      this.closeFormDialog()
    },
    createRecord() {
      this.data.push({ ...this.formDialog.draft })
      this.closeFormDialog()
    },
    deleteRecord(index) {
      return async() => this.data.splice(index, 1)
    },

    openURL(url) {
      window.location.href = url
    }
  }
}
</script>

<template>
  <div>
    <Block title="证书">
      <template v-if="isEditing" #extra>
        <el-button
          size="mini"
          type="primary"
          @click="showCreateDialog"
        >
          新增
        </el-button>

        <el-button
          size="mini"
          :loading="$attrs.isSubmitting"
          @click="$emit('save')"
        >
          保存
        </el-button>
      </template>

      <FormWithDialog
        ref="form"
        v-model="formDialog.draft"
        label-position="top"
        title="证书"
        :visible.sync="formDialog.visible"
        :confirm-text="formDialogConfirmBtnText"
        @cancel="closeFormDialog"
        @confirm="handleFormConfirm"
      />

      <el-table :data="certificateFormatted" border style="width: 100%">
        <el-table-column align="center" prop="name" label="证书名称" />
        <el-table-column align="center" prop="expireDate" label="到期时间" />

        <el-table-column align="center" label="附件">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="openURL(scope.row.attachment)"
            >
              <i class="el-icon-download" />
              下载
            </el-button>
          </template>
        </el-table-column>

        <el-table-column v-if="isEditing" label="操作">
          <template slot-scope="scope">
            <div class="row-actions">
              <el-button
                size="mini"
                type="text"
                @click="handleEditing(scope.$index,scope.row)"
              >
                编辑
              </el-button>

              <Popconfirm
                :confirm-fn="deleteRecord(scope.$index)"
                title="确定删除吗？"
              >
                <el-button
                  size="mini"
                  type="text"
                >
                  删除
                </el-button>
              </Popconfirm>
            </div>
          </template>
        </el-table-column>

      </el-table>
    </Block>
  </div>
</template>

<style lang="scss">
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: nowrap;
    padding: 20px 0;

    >.title {
        font-size: 16px;
        font-weight: 700;
        color: #303133;
    }

}
</style>
